<template>
  <div class="profile-page">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>

      <div v-loading="loading" class="profile-content">
        <!-- 用户基本信息展示 -->
        <div class="user-info-section">
          <div class="avatar-section">
            <el-avatar :size="100" :src="avatarUrl" />
            <div class="user-basic">
              <h3>{{ userName }}</h3>
              <p>{{ userAccount }}</p>
              <el-tag :type="userStatus === 1 ? 'success' : 'danger'">
                {{ userStatus === 1 ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 表单 -->
        <el-form
          ref="formRef"
          :model="formModel"
          :rules="rules"
          label-width="120px"
          class="profile-form"
        >
          <el-divider content-position="left">基本信息</el-divider>
          
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formModel.name" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formModel.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formModel.phone" placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="formModel.idNumber" placeholder="请输入身份证号" />
          </el-form-item>

          <el-divider content-position="left">账号信息</el-divider>

          <el-form-item label="用户名">
            <el-input v-model="formModel.username" disabled />
          </el-form-item>

          <el-form-item label="创建时间" v-if="formModel.createTime">
            <el-input v-model="formModel.createTime" disabled />
          </el-form-item>

          <el-form-item label="更新时间" v-if="formModel.updateTime">
            <el-input v-model="formModel.updateTime" disabled />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSave" :loading="saving">
              保存修改
            </el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="warning" @click="passwordDialogVisible = true">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordData"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordData.oldPassword"
            type="password"
            show-password
            placeholder="请输入原密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordData.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordData.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordChange" :loading="passwordSaving">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { employeeApi } from '@/api/index.js'
import defaultAvatar from '@/assets/avatar.svg'
import { useAppStore } from '@/stores/app'
import { useRouter } from 'vue-router'

const appStore = useAppStore()
const router = useRouter()

// 基础状态
const loading = ref(false)
const saving = ref(false)
const passwordSaving = ref(false)
const passwordDialogVisible = ref(false)

// 表单引用
const formRef = ref()
const passwordFormRef = ref()

// 用户展示信息
const userName = ref('未设置姓名')
const userAccount = ref('未设置账号')
const userStatus = ref(1)
const avatarUrl = ref(defaultAvatar)

// 表单数据模型
const formModel = ref({
  id: '',
  name: '',
  username: '',
  phone: '',
  sex: '1',
  idNumber: '',
  createTime: '',
  updateTime: ''
})

// 原始数据备份
const originalData = ref({})

// 密码表单数据
const passwordData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordData.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户ID
const getUserId = () => {
  return appStore.userInfo?.id || 
         JSON.parse(localStorage.getItem('userInfo') || '{}').id || 
         localStorage.getItem('userId') || 
         1
}

// 加载个人信息
const loadUserProfile = async () => {
  loading.value = true
  
  try {
    const userId = getUserId()
    console.log('正在加载用户信息，用户ID:', userId)
    
    const response = await employeeApi.getById(userId)
    console.log('API返回的完整响应:', response)
    
    if (response && response.data) {
      console.log('=== 直接使用response.data，不做任何处理 ===')
      console.log('response.data的具体内容:', response.data)
      
      // 真正的用户数据在response.data.data中
      const userData = response.data.data
      console.log('真正的用户数据:', userData)
      
      // 直接使用API数据，不添加默认值
      userName.value = userData.name
      userAccount.value = userData.username  
      userStatus.value = userData.status
      
      // 直接赋值，不做任何处理
      formModel.value = {
        id: userData.id,
        name: userData.name,
        username: userData.username,
        phone: userData.phone,
        sex: userData.sex,
        idNumber: userData.idNumber,
        createTime: userData.createTime,
        updateTime: userData.updateTime
      }
      
      // 备份原始数据
      originalData.value = { ...formModel.value }
      
      console.log('头部显示数据:', userName.value, userAccount.value, userStatus.value)
      console.log('表单数据:', formModel.value)
      
      ElMessage.success('个人信息加载成功')
    } else {
      ElMessage.error('未获取到用户数据')
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载个人信息失败')
  } finally {
    loading.value = false
  }
}

// 保存修改
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  saving.value = true
  
  try {
    const updateData = {
      id: formModel.value.id,
      name: formModel.value.name,
      username: formModel.value.username,
      phone: formModel.value.phone,
      sex: formModel.value.sex,
      idNumber: formModel.value.idNumber
    }
    
    console.log('提交的更新数据:', updateData)
    
    await employeeApi.update(updateData)
    
    // 更新显示信息
    userName.value = formModel.value.name
    userAccount.value = formModel.value.username
    
    // 更新备份数据
    originalData.value = { ...formModel.value }
    
    ElMessage.success('保存成功')
    
    // 保存成功后跳转到员工管理页面
    setTimeout(() => {
      router.push('/employee')
    }, 1000)
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 重置表单
const handleReset = () => {
  formModel.value = { ...originalData.value }
  ElMessage.info('已重置为原始数据')
}

// 修改密码
const handlePasswordChange = async () => {
  if (!passwordFormRef.value) return
  
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  passwordSaving.value = true
  
  try {
    const passwordUpdateData = {
      empId: formModel.value.id,
      oldPassword: passwordData.value.oldPassword,
      newPassword: passwordData.value.newPassword
    }
    
    await employeeApi.updatePassword(passwordUpdateData)
    
    // 清空密码表单
    passwordData.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
    
    passwordDialogVisible.value = false
    ElMessage.success('密码修改成功')
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    passwordSaving.value = false
  }
}

// 初始化
onMounted(() => {
  console.log('组件已挂载，开始加载数据')
  loadUserProfile()
})
</script>

<style scoped>
.profile-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.profile-card {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.profile-content {
  padding: 20px 0;
}

.user-info-section {
  margin-bottom: 30px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.user-basic h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #303133;
}

.user-basic p {
  margin: 0 0 12px 0;
  color: #909399;
  font-size: 14px;
}

.profile-form {
  max-width: 600px;
}

.profile-form .el-form-item {
  margin-bottom: 24px;
}

.profile-form .el-radio {
  margin-right: 20px;
}
</style>